package com.wzy.stream;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wzy
 * @Date: 2022/3/14 16:07
 * @Description:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Menu {
    private Integer id;
    private String category;
    private Integer parentId;
    private List<Menu> menuList;


    public Menu(Integer id, String category, Integer parentId) {
        this.id = id;
        this.category = category;
        this.parentId = parentId;
    }
}

class Test {
    public static void main(String[] args) {
        /**
         * 注意不能有循环！
         */
        List<Menu> menus = Arrays.asList(new Menu(99, "分类", 0),
                new Menu(1, "分类1.1", 99),
                new Menu(2, "分类1.2", 99),
                new Menu(3, "分类1.3", 99),
                new Menu(4, "分类1.1.1", 1),
                new Menu(5, "分类1.1.2", 1),
                new Menu(6, "分类1.2.1", 2),
                new Menu(7, "分类1.2.2", 2),
                new Menu(8, "分类1.1.1.1", 4),
                new Menu(9, "分类1.1.2.1", 5),
                new Menu(10, "分类1.2.1.1", 6)
        );
        List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(m -> {
            m.setMenuList(getMenuList(m.getId(), menus));
            return m;
        }).collect(Collectors.toList());
        System.out.println(JSONObject.toJSONString(collect));
    }

    private static List<Menu> getMenuList(int parentId, List<Menu> menuList) {
        List<Menu> collect = menuList.stream().filter(m -> m.getParentId() == parentId).map(m -> {
            m.setMenuList(getMenuList(m.getId(), menuList));
            return m;
        }).collect(Collectors.toList());
        return collect;
    }
}
